package cn.kgm.makeGodV2.ruleEngine;

import java.util.*;

/**
 * @Version 1.8
 * @Author: Kappi
 * @Date: 2025-9-24 10:26
 * @Description: cn.kgm.makeGodV2.ruleEngine.RuleEngine
 */
// 规则引擎
public class RuleEngine {
    private static RuleEngine instance;
    private final Map<String, RuleStrategy<?>> ruleStrategyMap = new HashMap<>();
    private final List<RuleStrategy<?>> ruleStrategies = new ArrayList<>();

    private RuleEngine() {
        // 私有构造，防止外部实例化
    }

    // 单例模式
    public static RuleEngine getInstance() {
        if (instance == null) {
            instance = new RuleEngine();
        }
        return instance;
    }

    // 注册规则
    public void registerRule(RuleStrategy<?> ruleStrategy) {
        String ruleType = ruleStrategy.getRuleType();
        if (ruleStrategyMap.containsKey(ruleType)) {
            System.out.println("警告: 规则类型 " + ruleType + " 已存在，将被覆盖");
        }

        ruleStrategyMap.put(ruleType, ruleStrategy);

        // 移除已存在的同类型规则（如果存在）
        ruleStrategies.removeIf(strategy -> strategy.getRuleType().equals(ruleType));
        ruleStrategies.add(ruleStrategy);

        // 按优先级排序
        ruleStrategies.sort(Comparator.comparingInt(RuleStrategy::getPriority));

        System.out.println("注册规则: " + ruleType + " (优先级: " + ruleStrategy.getPriority() + ")");
    }

    // 根据类型获取规则
    @SuppressWarnings("unchecked")
    public <T> RuleStrategy<T> getRuleStrategy(String ruleType) {
        RuleStrategy<?> strategy = ruleStrategyMap.get(ruleType);
        if (strategy == null) {
            throw new IllegalArgumentException("未找到规则策略: " + ruleType);
        }
        return (RuleStrategy<T>) strategy;
    }

    // 执行单个规则
    public <T> RuleResult<T> executeRule(String ruleType, RuleContext context) {
        try {
            RuleStrategy<T> strategy = getRuleStrategy(ruleType);

            if (!strategy.validate(context)) {
                return RuleResult.fail("规则条件不满足: " + ruleType);
            }

            return strategy.execute(context);
        } catch (Exception e) {
            return RuleResult.fail("规则执行异常: " + e.getMessage());
        }
    }

    /**
     * 根据规则类型获取规则策略（不执行）
     */
    public RuleStrategy<?> getStrategy(String ruleType) {
        RuleStrategy<?> strategy = ruleStrategyMap.get(ruleType);
        if (strategy == null) {
            throw new IllegalArgumentException("未找到规则策略: " + ruleType);
        }
        return strategy;
    }

    // 批量执行规则
    public List<RuleResult<?>> executeRules(RuleContext context) {
        List<RuleResult<?>> results = new ArrayList<>();

        for (RuleStrategy<?> strategy : ruleStrategies) {
            if (strategy.validate(context)) {
                try {
                    RuleResult<?> result = strategy.execute(context);
                    results.add(result);
                } catch (Exception e) {
                    results.add(RuleResult.fail("执行异常: " + e.getMessage()));
                }
            }
        }

        return results;
    }

    // 获取所有规则类型
    public Set<String> getRegisteredRuleTypes() {
        return new HashSet<>(ruleStrategyMap.keySet());
    }

    // 清空所有规则（用于测试或重置）
    public void clearRules() {
        ruleStrategyMap.clear();
        ruleStrategies.clear();
    }
}
